import axios from 'axios'
import CONSTANTS from 'constants'
// import baseConfig from '../config'

const fetchConfig = () => {
  const config = {
    get: {
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
        'token': localStorage.getItem('token') || ''
      }
    },
    post: {
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
        // 'Content-Type': 'application/x-www-form-urlencoded',
        'token': localStorage.getItem('token') || ''
      }
    }
  }
  return config
}

const instance = axios.create({
  baseURL: '/',
  timeout: 20000,
  headers: { Accept: '*/*' }
})

instance.interceptors.request.use(request => {
  let domain
  switch (process.env.NODE_ENV) {
    case 'local':
      domain = ''
      break
    case 'development':
      // domain = 'http://119.3.137.185:8085'
      domain = ''
      break
    case 'production':
      // domain = 'http://119.3.137.185:8085'
      domain = ''
      break

    default:
      break
  }
  request.url = domain + request.url
  const data = request.params
  const config = fetchConfig()
  request.params = {
    t: Date.now()
  }

  if (request.method === 'get') {
    request.params['data'] = data || {}
    request.headers['Content-Type'] = config['get']['headers']['Content-Type']
    request.headers['X-MARS-TOKEN'] = config['get']['headers']['X-MARS-TOKEN']
  }

  if (request.method === 'post') {
    // request.data =
    //   'data=' + encodeURIComponent(JSON.stringify(request.data || {}))
    request.headers['Content-Type'] = config['post']['headers']['Content-Type']
    request.headers['X-MARS-TOKEN'] = config['post']['headers']['X-MARS-TOKEN']
  }
  request.headers['token'] = localStorage.getItem('token') || ''
  return request
})

instance.interceptors.response.use(
  ({ data }) => {
    if (data.code === CONSTANTS.NEED_LOGIN) {
      localStorage.removeItem('token')
      location.href = '/login'
    }
    if (!data.success) {
      window.showError(data)
    }
    return data
  },
  err => {
    let error
    if (err.code === 'ECONNABORTED' && err.message.indexOf('timeout') !== -1) {
      error = {
        code: '-1',
        msg: '请求超时未响应'
      }
    } else {
      error = {
        code: `${(err && err.response && err.response.status) || '-1'}`,
        msg: (err && err.message) || '未知错误'
      }
    }
    return window.showError(error)
  }
)

export default instance
